var prifix = '';


var RESERVATIONCENTERURL = {                                                        //预约中心

    addReservation: {                                                                //添加预约
        store: prifix + '/reserve/store',
    },
    reservationList: {                                                              //预约列表页面
        index: prifix + '/reserve/index',                                         //预约列表
        edit: prifix + '/reserve/edit',
        update: prifix + '/reserve/update',                                      //更新诊室
        destroy: prifix + '/reserve/destroy',                                      //解除预约
        notify: prifix + '/reserve/notify'                                        //发送短信
    },
    statistical: {                                                                   //统计页面
        doctor: {                                                                    //医生统计页面
            statistics: prifix + '/reserve/statistics/situation'                    //查询图表信息
        },
        admin: {
            visit: prifix + '/reserve/statistics/visit'
        }


    },
    doctorManagement: {                                                              //医生管理
        doctor: {                                                                    //医生页面
            store: prifix + '/reserve/schedule/store',
            update: prifix + '/reserve/schedule/update',
            plan: prifix + '/reserve/schedule/plan',
            planOfMonth: prifix + '/reserve/schedule/planOfMonth',
            storeWithAMonth: prifix + '/reserve/schedule/storeWithAMonth',
            destroyMonth: prifix + '/reserve/schedule/destroyMonth',
            planInMonthAfterNow: prifix + '/reserve/schedule/planInMonthAfterNow'
        },
        admin: {                                                                     //管理员页面
            index: prifix + '/manage/doctor',
            store: prifix + '/manage/doctor/store',
            update: prifix + '/manage/doctor/update',
            destroy: prifix + '/manage/doctor/destroy',
            edit: prifix + '/manage/doctor/edit'
        }
    },
    patientPool: {
        doctor: {                                                                    //医生用户
            index: prifix + '/reserve/pool/index',
            reject: prifix + '/reserve/pool/reject',
            accept: prifix + '/reserve/pool/accept'
        },
        admin: {
            assignTo: prifix + '/reserve/pool/assignTo',
            doctors: prifix + '/reserve/pool/doctors'
        }
    },
    messageCenter: {
        index: prifix + '/reserve/message',
        unread: prifix + '/reserve/message/unread'
    }

};


//confirm 弹窗  start
function confirmModel(title, body, okBtn, cancelBtn, okHidden) {
    if (!title) {
        title = '温馨提示';
    }
    if (!body) {
        body = '确定要删除吗？';
    }
    if (!okBtn) {
        okBtn = '确定';
    }
    if (!cancelBtn) {
        cancelBtn = '取消';
    }
    $.confirm({
        title: title,
        body: body,
        okBtn: okBtn,
        cancelBtn: cancelBtn,
        transition: true,
        okHidden: function () {
            okHidden();
        }
    });
}

//confirm 弹窗  end

//alert 弹窗  start
function alertModel(title, body) {
    if (!title) {
        title = '温馨提示';
    }
    if (!body) {
        body = '出错了，再来一次！';
    }
    $.alert({
        title: title,
        body: body,
        transition: true
    });
}

//alert 弹窗  end

// ajax 请求 start
function ajaxGet(url, data, success, error) {
    $.ajax({
        type: "get",
        url: url,
        data: data,
        dataType: "json",
        beforeSend: function () {
            $('.loading').removeClass('display-none');
        },
        success: function (data) {
            $('.loading').addClass('display-none');
            if (typeof data == 'string') {
                data = $.parseJSON(data);
            }
            success(data);
        },
        error: function (x, t, e) {
            $('.loading').addClass('display-none');
            if (error === undefined) {
                if (t == 'timeout') {
                    console.log('请求超时');
                }
            } else {
                error(x, t, e);
            }

        }
    });
}

function ajaxPost(url, data, success, error) {
    $.ajax({
        type: "post",
        url: url,
        data: data,
        dataType: "json",
        beforeSend: function () {
            $('.loading').removeClass('display-none');
        },
        success: function (data) {
            $('.loading').addClass('display-none');
            if (typeof data == 'string') {
                data = $.parseJSON(data);
            }
            success(data);
        },
        error: function (x, t, e) {
            $('.loading').addClass('display-none');
            if (error === undefined) {
                if (t == 'timeout') {
                    console.log('请求超时');
                }
            } else {
                error(x, t, e);
            }

        }
    });
}

// ajax 请求 end

// 页码函数方法  start
var pageNum = 0;

function page(id, data, fun, param) {
    var totalPages = Math.ceil(data.last_page);
    $('#' + id).jqPaginator({
        totalPages: totalPages,//分页总页数
        visiblePages: 5,//最多显示的页码数
        currentPage: data.current_page,//当前页码
        first: '',//首页
        last: '',//末页
        onPageChange: function (e) {//回调函数，换页时触发，传入目标页
            param.page = e;
            pageNum = e;
            fun(param);
        }
    })
}

// 页码函数方法  end

// 日历限制最小(大)可选日期为当日  start
var date = new Date();

function formatDate(date) {
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? '0' + m : m;
    var d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    return y + '-' + m + '-' + d;
};
$('.limitStartData').datepicker({
    startDate: formatDate(date)
});
$('.limitEndData').datepicker({
    endDate: formatDate(date)
});
// 日历限制最小(大)可选日期为当日  end

//对一个日期相加（减）天数计算 方法  start
function addDate(date, days) {
    var d = new Date(date);
    d.setDate(d.getDate() + days);
    var month = d.getMonth() + 1;
    var day = d.getDate();
    if (month < 10) {
        month = "0" + month;
    }
    if (day < 10) {
        day = "0" + day;
    }
    var val = d.getFullYear() + "-" + month + "-" + day;
    return val;
}

//对一个日期相加（减）天数计算 方法  end

//将系统日期变为 yyyy-mm-dd h:m:s   格式   start
function formatTen(num) {
    return num > 9 ? (num + "") : ("0" + num);
}

function formatDate(date, h, m, s) {
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    var hour = date.getHours();
    var minute = date.getMinutes();
    var second = date.getSeconds();
    var time = year + "-" + formatTen(month) + "-" + formatTen(day);
    if (h) {
        time += ' ' + hour;
        if (m) {
            time += ':' + minute;
            if (s) {
                time += ':' + second;
            }
        }
    }
    return time
}

//将系统日期变为 yyyy-mm-dd h:m:s   格式   end

//获取日期对应星期几  start
function getWeek(data) {
    var weekArr = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
    var week = weekArr[new Date(data).getDay()];
    return week;
}

//获取日期对应星期几  end

//模态框 层上层提示点击周围关闭层  start
$('body').delegate('div.alertZindex', 'click', function () {
    $('.sui-modal-backdrop').removeClass('alertZindex');
});
//模态框 层上层提示点击周围关闭层  end

//ie 低版本  maxLength 属性  start
$('body').find('textarea').change(function () {
    var len = $(this).attr('maxLength');
    var val = $(this).val();
    $(this).val(val.substring(0, len));
});
$('body').find('input:not(:file)').change(function () {
    var len = $(this).attr('maxLength');
    var val = $(this).val();
    $(this).val(val.substring(0, len));
});
//ie 低版本  maxLength 属性  end

//手机号11位 且 符合规则 监测  start
$('input.phoneLength').bind('input.phoneLength propertychange', function () {
    var reg = /^\d+$/;
    if ($(this).val().length > 11) {
        $(this).val($(this).val().slice(0, 11));
    } else {
        if (!(reg.test($(this).val()))) {
            $(this).val($(this).val().slice(0, $(this).val().length - 1));
        }
    }
});

function checkPhone(val) {
    var reg = /^1[345789]{1}\d{9}$/;
    if (val) {
        val = val.trim();
        if (reg.test(val)) {
            return true;
        }
        else {
            return false;
        }
    }
    else {
        return true;
    }
}

//手机号11位 且 符合规则 监测  end

//姓名 16个字符监测  start
function chkstrlen(str) {
    var strlen = 0;
    for (var i = 0; i < str.length; i++) {
        if (str.charCodeAt(i) > 255) //如果是汉字，则字符串长度加2
            strlen += 2;
        else
            strlen++;
    }
    return strlen;
}

function checkName(nameStr) {
    var reg = /^([\u4E00-\uFA29]*[0-9]*[a-z]*[A-Z]*)+$/;
    if (nameStr) {
        nameStr = nameStr.trim();
        if ((reg.test(nameStr)) && (chkstrlen(nameStr))) {
            return true;
        }
        else {
            return false;
        }
    }
    else {
        return true;
    }
}

//姓名 16个字符监测  end

//密码  6-16位数字 字母  或者两者组合  start
function checkPassword(pwd) {
    var reg = /^[A-Za-z0-9]{6,16}$/;
    if (reg.test(pwd)) {
        return true;
    } else {
        return false;
    }
}

//密码  6-16位数字 字母  或者两者组合  end

// 检测两个时间大小 (第三个参数没有 默认 结束时间大于开始时间)  start
function checkTwoDate(star_time, end_time, endLessStart) {
    var now = new Date();
    if (star_time && end_time) {
        // 结束时间
        var edate = end_time.split('-');
        var end = new Date(edate[0], edate[1] - 1, edate[2]);
        // 开始时间
        var sdate = star_time.split('-');
        var start = new Date(sdate[0], sdate[1] - 1, sdate[2]);
        if (endLessStart) {
            if (end - start <= 0) {
                return true;
            } else {
                return false;
            }
        } else {
            if (end - start >= 0) {
                return true;
            } else {
                return false;
            }
        }
    } else {
        return true;
    }
}

// 检测两个时间大小 (第三个参数没有 默认 结束时间大于开始时间)  end

//人数类型 1-999 输入框限制  start
$('body').delegate('.peopleInput', 'blur', function () {
    dealNum($(this), 1, 1, 999, 999, 0);
});
//人数类型 1-999 输入框限制  end


//退出跳转
function aClick() {
    //跳转
    window.location.pathname = "/manage/auth/logout";
    //清除缓存
    sessionStorage.clear();
    localStorage.clear();
};

//用户管理病史日期   author  ztq
$('.maxMonth').datepicker({
    minViewMode: 2,
    format: 'yyyy',
    endDate: formatDate(date)
});
//日历最多显示到月  end

//用户管理头像上传   author  ztq
// 上传预览图片
function preview(file) {//预览图片得到图片base64
    var prevDiv = document.getElementById('preview');
    var s = file;
    console.log(s);

    var file = file.files[0];
    console.log(file);

    try {
        if (!/image\/\w+/.test(file.type)) {
            alert('选择的不是图片');
            return false;
        } else {
            var reader = new FileReader();
            reader.onload = function (evt) {
                prevDiv.innerHTML = '<img src="' + evt.target.result + '" />';
            }
            reader.readAsDataURL(file);
        }
    }
    catch (err) {

    }

}

//体格检查计算 BMI的值  start
function getBMI(stature, weight) {
    if (isNaN(stature) || stature < 0) {
        alertModel('', '请正确填写身高的值！');
        return false;
    } else {
        if (isNaN(weight) || weight < 0) {
            alertModel('', '请正确填写体重的值！');
            return false;
        } else {
            stature = stature / 100;
            var val = parseFloat(weight / (stature * stature));
            val = parseFloat(val.toFixed(2));
            val = val.toFixed(2);
            $('#addDoctor #bmi').val(val);
        }
    }
}

$('#addDoctor input[name="weight"],#addDoctor input[name="height"]').blur(function () {
    var weight = $('#addDoctor input[name="weight"]').val();
    var stature = $('#addDoctor input[name="height"]').val();
    if (weight && stature) {
        getBMI(stature, weight);
    }
});
// 体格检查计算 BMI的值end
// 治疗方式 选中
$('.cureMethod').delegate(".cureMethod_span", "click", function () {
    var _this = $(this);
    _this.toggleClass('on');
    if (_this.text() == '暂无') {
        _this.siblings('span').removeClass('on')
    } else if (_this.text() != '暂无') {
        $('#cureMethod span:last').removeClass('on')
    }
})


// 图片剪切对应的js初始化⬇️
$(function () {

    'use strict';

    var console = window.console || {
        log: function () {
        }
    };
    var URL = window.URL || window.webkitURL;
    var $image = $('#image');
    var $download = $('#download');
    var $dataX = $('#dataX');
    var $dataY = $('#dataY');
    var $dataHeight = $('#dataHeight');
    var $dataWidth = $('#dataWidth');
    var $dataRotate = $('#dataRotate');
    var $dataScaleX = $('#dataScaleX');
    var $dataScaleY = $('#dataScaleY');
    var options = {
        aspectRatio: 1 / 1,//比例设置
        preview: '.img-preview',
        crop: function (e) {
            $dataX.val(Math.round(e.detail.x));
            $dataY.val(Math.round(e.detail.y));
            $dataHeight.val(Math.round(e.detail.height));
            $dataWidth.val(Math.round(e.detail.width));
            $dataRotate.val(e.detail.rotate);
            $dataScaleX.val(e.detail.scaleX);
            $dataScaleY.val(e.detail.scaleY);
        }
    };
    var originalImageURL = $image.attr('src');
    var uploadedImageName = 'cropped.jpg';
    var uploadedImageType = 'image/jpeg';
    var uploadedImageURL;


    // Tooltip
    $('[data-toggle="tooltip"]').tooltip();


    // Cropper
    $image.on({
        ready: function (e) {
            // console.log(e.type);
        },
        cropstart: function (e) {
            // console.log(e.type, e.detail.action);
        },
        cropmove: function (e) {
            // console.log(e.type, e.detail.action);
        },
        cropend: function (e) {
            // console.log(e.type, e.detail.action);
        },
        crop: function (e) {
            // console.log(e.type);
        },
        zoom: function (e) {
            // console.log(e.type, e.detail.ratio);
        }
    }).cropper(options);


    // Buttons
    if (!$.isFunction(document.createElement('canvas').getContext)) {
        $('button[data-method="getCroppedCanvas"]').prop('disabled', true);
    }

    if (typeof document.createElement('cropper').style.transition === 'undefined') {
        $('button[data-method="rotate"]').prop('disabled', true);
        $('button[data-method="scale"]').prop('disabled', true);
    }


    // Download
    if (typeof $download[0].download === 'undefined') {
        $download.addClass('disabled');
    }


    // Options
    $('.docs-toggles').on('change', 'input', function () {
        var $this = $(this);
        var name = $this.attr('name');
        var type = $this.prop('type');
        var cropBoxData;
        var canvasData;

        if (!$image.data('cropper')) {
            return;
        }

        if (type === 'checkbox') {
            options[name] = $this.prop('checked');
            cropBoxData = $image.cropper('getCropBoxData');
            canvasData = $image.cropper('getCanvasData');

            options.ready = function () {
                $image.cropper('setCropBoxData', cropBoxData);
                $image.cropper('setCanvasData', canvasData);
            };
        } else if (type === 'radio') {
            options[name] = $this.val();
        }

        $image.cropper('destroy').cropper(options);
    });


    // Methods
    $('.docs-buttons').on('click', '[data-method]', function () {
        var $this = $(this);
        var data = $this.data();
        var cropper = $image.data('cropper');
        var cropped;
        var $target;
        var result;

        if ($this.prop('disabled') || $this.hasClass('disabled')) {
            return;
        }

        if (cropper && data.method) {
            data = $.extend({}, data); // Clone a new one

            if (typeof data.target !== 'undefined') {
                $target = $(data.target);

                if (typeof data.option === 'undefined') {
                    try {
                        data.option = JSON.parse($target.val());
                    } catch (e) {
                        console.log(e.message);
                    }
                }
            }

            cropped = cropper.cropped;

            switch (data.method) {
                case 'rotate':
                    if (cropped && options.viewMode > 0) {
                        $image.cropper('clear');
                    }

                    break;

                case 'getCroppedCanvas':
                    if (uploadedImageType === 'image/jpeg') {
                        if (!data.option) {
                            data.option = {};
                        }

                        data.option.fillColor = '#fff';
                    }

                    break;
            }

            result = $image.cropper(data.method, data.option, data.secondOption);


            // var img=convertCanvasToImage(result);
            // $("#showImg").attr('src',img.src);
            // console.log(convertCanvasToImage(result));

            var base64Str=result.toDataURL(uploadedImageType);
            // console.log(base64Str);


            var formData = new FormData();
            formData.append("image", convertBase64UrlToBlob(base64Str));
            $.ajax({
                url: '/resources/image/upload',
                dataType: 'JSON',
                anync: false,
                cache: false,
                processData: false,
                contentType: false,
                type: 'post',
                data: formData,
                success: function (data) {
                    console.log(data);
                    if (data.code == 10000) {
                        $("#imgUpload").val(data.data.url)
                    } else {
                        alertModel('温馨提示', data.message)
                    }
                }

            })



            switch (data.method) {
                case 'rotate':
                    if (cropped && options.viewMode > 0) {
                        $image.cropper('crop');
                    }

                    break;

                case 'scaleX':
                case 'scaleY':
                    $(this).data('option', -data.option);
                    break;

                case 'getCroppedCanvas':
                    if (result) {
                        // Bootstrap's Modal
                        // $('#getCroppedCanvasModal').modal().find('.modal-body').html(result);
                        $("#showImg").html(result);

                        if (!$download.hasClass('disabled')) {
                            download.download = uploadedImageName;
                            $download.attr('href', result.toDataURL(uploadedImageType));
                        }
                    }

                    break;

                case 'destroy':
                    if (uploadedImageURL) {
                        URL.revokeObjectURL(uploadedImageURL);
                        uploadedImageURL = '';
                        $image.attr('src', originalImageURL);
                    }

                    break;
            }

            if ($.isPlainObject(result) && $target) {
                try {
                    $target.val(JSON.stringify(result));
                } catch (e) {
                    console.log(e.message);
                }
            }

        }
    });


    // Keyboard
    $(document.body).on('keydown', function (e) {

        if (!$image.data('cropper') || this.scrollTop > 300) {
            return;
        }

        switch (e.which) {
            case 37:
                e.preventDefault();
                $image.cropper('move', -1, 0);
                break;

            case 38:
                e.preventDefault();
                $image.cropper('move', 0, -1);
                break;

            case 39:
                e.preventDefault();
                $image.cropper('move', 1, 0);
                break;

            case 40:
                e.preventDefault();
                $image.cropper('move', 0, 1);
                break;
        }

    });


    // Import image
    var $inputImage = $('#inputImage');

    if (URL) {
        $inputImage.change(function () {
            var files = this.files;
            var file;

            if (!$image.data('cropper')) {
                return;
            }

            if (files && files.length) {
                file = files[0];

                if (/^image\/\w+$/.test(file.type)) {
                    uploadedImageName = file.name;
                    uploadedImageType = file.type;

                    if (uploadedImageURL) {
                        URL.revokeObjectURL(uploadedImageURL);
                    }

                    uploadedImageURL = URL.createObjectURL(file);
                    $image.cropper('destroy').attr('src', uploadedImageURL).cropper(options);
                    $inputImage.val('');
                } else {
                    window.alert('Please choose an image file.');
                }
            }
        });
    } else {
        $inputImage.prop('disabled', true).parent().addClass('disabled');
    }

    function convertCanvasToImage(canvas) {
        var image = new Image();
        image.src = canvas.toDataURL("image/png");
        return image;
    }

    // chuan⬇️
    $(".head_file").click(function () {
        $("#inputImage").click();
    });
    $("#inputImage").change(function () {

        $("#headPic").show();
    });

    $("#btnCutSure").click(function () {
        $("#headPic").hide();
    });


});


/**  
  * 将以base64的图片url数据转换为Blob  
  * @param urlData  
  *            用url方式表示的base64图片数据  
  */
function convertBase64UrlToBlob(urlData) {

    var bytes = window.atob(urlData.split(',')[1]);        //去掉url的头，并转换为byte  

    //处理异常,将ascii码小于0的转换为大于0  
    var ab = new ArrayBuffer(bytes.length);
    var ia = new Uint8Array(ab);
    for (var i = 0; i < bytes.length; i++) {
        ia[i] = bytes.charCodeAt(i);
    }

    return new Blob([ab], {type: 'image/png'});
}
